﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using AcctrueWMS.Foundation.Data;
using System.Data;
using AcctrueWMS.Foundation.DAL;
using System.Web;

namespace AcctrueWMS.Foundation.Web
{
    public class LoginValidator
    {

        /// <summary>
        /// 验证session
        /// </summary>
        /// <param name="userName">用户名</param>
        /// <param name="passport">密码</param>
        /// <param name="logMessage">提示信息</param>
        /// <returns>bool</returns>
        public Boolean ValidateLogin(string userName, string passport, out string logMessage)
        {
            logMessage = string.Empty;
            if (!string.IsNullOrEmpty(userName))
            {
                IDataModelContext logContext = Runtime.Context;
                string sqlLoginCondition = " where userName='" + userName + " and passport='" + passport + "' ";
                logContext.FilePath = Runtime.ModelFilePath;
                DataModel model = null; new DataModel(logContext, "userInfo");
                logContext.Select(model, sqlLoginCondition);
                if (model.Rows.Count > 0)
                {
                    PersistLoggedUser(model);
                }
                else
                {
                    logMessage = "用户名或密码不正确，登陆失败！";
                    return false;
                }
                return true;
            }
            else
            {
                logMessage = "登陆名为空！";
                return false;
            }
        }
        /// <summary>
        /// 将登陆用户信息存在Session中
        /// </summary>
        /// <param name="model"></param>
        private void PersistLoggedUser(DataModel model)
        {
            StringBuilder sb = new StringBuilder();
            DataTable dt = WMSqlExcuter.ExecuteDataTable(" select * from userRoleInfo where userNo='" + model.Rows[0][model.KeyColumnName] + "'");
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                sb.Append(dt.Rows[i]["roleCode"].ToString() + ",");
            }
            if (sb.Length > 0)
            {
                sb.Remove(sb.Length - 1, 1);
            }
            HttpContext.Current.Session.Remove(WMSSessionKeys.CurrentUser);
            HttpContext.Current.Session.Add(WMSSessionKeys.CurrentUser, new CurrentUser()
            {
                DisplayName = model.Rows[0]["displayName"].Value.ToString(),
                RoleCodes = sb.ToString(),
                UserName = model.Rows[0]["userName"].ToString(),
                UserNo = model.Rows[0]["userNo"].ToString()

            });

        }
    }



}
